import tkinter as tk
from tkinter import ttk,filedialog, messagebox
import os
import time
import threading
import keyboard
from mouse_tracker import MouseClickTracker
from visual_canvas import EnhancedVisualOperationCanvas
from sequence_manager import OperationSequenceManager


class EnhancedOperationConfigWindow:
    """增强版自定义操作配置窗口 - 使用新的可视化画布"""
    def __init__(self, sequence_manager=None):
        self.root = tk.Tk()
        self.root.title("增强版自定义操作面板")
        
        # 获取屏幕分辨率并自动调整窗口大小
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        
        # 根据屏幕分辨率设置窗口大小（占用屏幕的70%）
        window_width = int(screen_width * 0.7)
        window_height = int(screen_height * 0.8)
        
        # 设置窗口位置居中
        x = (screen_width - window_width) // 2
        y = (screen_height - window_height) // 2
        
        self.root.geometry(f"{window_width}x{window_height}+{x}+{y}")
        
        # 设置最小尺寸为屏幕的40%
        min_width = int(screen_width * 0.4)
        min_height = int(screen_height * 0.4)
        self.root.minsize(min_width, min_height)
        
        # 设置淡蓝色主题颜色 
        self.theme_colors = { 
            'primary': '#F0F8FF',      # 淡蓝色背景 (AliceBlue)
            'secondary': '#B0E0E6',    # 中等淡蓝色 (PowderBlue)
            'accent': '#1E90FF',       # 强调色 (DodgerBlue)
            'text': '#000080',         # 深蓝色文字 (Navy)
            'button': '#4169E1',       # 按钮颜色 (RoyalBlue)
            'button_hover': '#6495ED', # 按钮悬停色 (CornflowerBlue)
            'success': '#90EE90',      # 成功色 (LightGreen)
            'warning': '#FFD700',      # 警告色 (保持金色)
            'error': '#FFB6C1'         # 错误色 (保持粉色)
        }
        
        # 设置应用图标
        try:
            icon_path = os.path.join(os.path.dirname(__file__), "icon.png")
            if os.path.exists(icon_path):
                icon_image = tk.PhotoImage(file=icon_path)
                self.root.iconphoto(True, icon_image)
        except Exception as e:
            print(f"设置图标失败: {e}")
            
        # 设置窗口背景色
        self.root.configure(bg=self.theme_colors['primary'])
        
        # 操作序列管理器
        self.sequence_manager = sequence_manager or OperationSequenceManager()
        
        # 创建主容器，使用网格布局实现更好的响应式设计
        main_container = tk.Frame(self.root, bg=self.theme_colors['primary'])
        main_container.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 创建左右分栏，使用权重分配空间（左侧30%，右侧70%）
        left_frame = tk.Frame(main_container, bg=self.theme_colors['primary'])
        left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 5))
        
        right_frame = tk.Frame(main_container, bg=self.theme_colors['primary'])
        right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=(5, 0))
        
        # 左侧：操作配置面板（限制宽度）
        self.setup_config_panel(left_frame)
        
        # 右侧：增强版可视化操作画布（分配更多空间）
        self.visual_canvas = EnhancedVisualOperationCanvas(right_frame)
        
        # 设置画布选择回调
        self.visual_canvas.on_operation_select_callback = self.on_canvas_operation_select
        
        # 绑定操作类型变化事件
        self.operation_type.trace('w', self.on_operation_type_change)
        
        # 加载现有操作序列到界面
        self._load_sequence_to_ui()

    def _load_sequence_to_ui(self):
        """将操作序列加载到界面"""
        operation_sequence = self.sequence_manager.operation_sequence
        for operation in operation_sequence:
            self.visual_canvas.add_operation(operation)
        self.update_operation_list()

    def on_canvas_operation_select(self, index):
        """画布操作选择回调"""
        # 更新列表选择
        self.operation_listbox.selection_clear(0, tk.END)
        if 0 <= index < self.operation_listbox.size():
            self.operation_listbox.select_set(index)
            self.operation_listbox.see(index)

    def get_operation_sequence(self):
        """获取操作序列"""
        return self.sequence_manager.operation_sequence
   
    def add_operation_to_canvas(self, operation):
        """添加操作到画布"""
        self.visual_canvas.add_operation(operation)
        
    def clear_canvas(self):
        """清空画布"""
        self.visual_canvas.clear_canvas()
        
    def remove_selected_operation_from_canvas(self):
        """从画布中移除选中的操作"""
        if self.visual_canvas.selected_operation:
            self.visual_canvas.remove_operation(self.visual_canvas.selected_operation)
        
    def on_canvas_operation_select(self, index):
        """画布操作选择回调"""
        # 更新列表选择
        self.operation_listbox.selection_clear(0, tk.END)
        if 0 <= index < self.operation_listbox.size():
            self.operation_listbox.select_set(index)
            self.operation_listbox.see(index)
        
    def setup_config_panel(self, parent):
        """设置操作配置面板 - 响应式布局"""
        # 创建主容器，使用权重分配垂直空间
        main_container = tk.Frame(parent, bg=self.theme_colors['primary'])
        main_container.pack(fill=tk.BOTH, expand=True)
        
        # 操作序列列表 - 使用权重分配，占据60%的垂直空间
        listbox_frame = tk.LabelFrame(main_container, text="操作序列", font=("微软雅黑", 11, "bold"),
                                    bg=self.theme_colors['primary'], fg=self.theme_colors['text'],
                                    relief=tk.GROOVE, bd=2)
        listbox_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        
        # 移除固定高度，使用fill=tk.BOTH和expand=True实现响应式
        self.operation_listbox = tk.Listbox(listbox_frame, font=("微软雅黑", 9),
                                        bg='white', fg=self.theme_colors['text'],
                                        selectbackground=self.theme_colors['accent'])
        self.operation_listbox.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        self.operation_listbox.bind('<<ListboxSelect>>', self.on_listbox_select)
        self.operation_listbox.bind('<Double-Button-1>', self.on_listbox_double_click)
        
        # 操作配置框架 - 使用固定高度，占据25%的垂直空间
        operation_frame = tk.LabelFrame(main_container, text="操作配置", font=("微软雅黑", 11, "bold"),
                                    bg=self.theme_colors['primary'], fg=self.theme_colors['text'],
                                    relief=tk.GROOVE, bd=2)
        operation_frame.pack(fill=tk.X, padx=5, pady=5)
        
        type_frame = tk.Frame(operation_frame, bg=self.theme_colors['primary'])
        type_frame.pack(fill=tk.X, pady=8)
        tk.Label(type_frame, text="操作类型:", font=("微软雅黑", 10, "bold"),
                bg=self.theme_colors['primary'], fg=self.theme_colors['text']).pack(side=tk.LEFT)
        
        self.operation_type = tk.StringVar(value="click")
        operation_types = [("点击", "click"), ("滚动", "scroll"), ("键盘输入", "keyboard")]
        for text, value in operation_types:
            tk.Radiobutton(type_frame, text=text, variable=self.operation_type, 
                        value=value, font=("微软雅黑", 9),
                        bg=self.theme_colors['primary'], fg=self.theme_colors['text'],
                        selectcolor=self.theme_colors['secondary']).pack(side=tk.LEFT, padx=10)
        
        # 参数配置 - 使用响应式布局
        self.setup_parameters(operation_frame)
        
        # 按钮框架 - 使用固定高度，占据15%的垂直空间
        self.setup_buttons(main_container)
        
    def setup_parameters(self, parent):
        """设置参数配置 - 使用响应式布局"""
        # 使用网格布局替代固定宽度
        param_frame = tk.Frame(parent, bg=self.theme_colors['primary'])
        param_frame.pack(fill=tk.X, padx=5, pady=5)
        
        # 第一行：坐标和滚动参数
        row1_frame = tk.Frame(param_frame, bg=self.theme_colors['primary'])
        row1_frame.pack(fill=tk.X, pady=3)
        
        # 坐标输入 - 使用响应式布局
        tk.Label(row1_frame, text="坐标 (x,y):", font=("微软雅黑", 9),
                bg=self.theme_colors['primary'], fg=self.theme_colors['text']).pack(side=tk.LEFT, padx=(0, 5))
        self.coord_entry = tk.Entry(row1_frame, font=("微软雅黑", 9),
                                bg='white', fg=self.theme_colors['text'])
        self.coord_entry.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)
        
        # 点击获取坐标按钮
        self.click_get_btn = tk.Button(row1_frame, text="点击获取坐标", 
                                    command=self.start_click_tracking,
                                    font=("微软雅黑", 9), bg=self.theme_colors['button'],
                                    fg='white', activebackground=self.theme_colors['button_hover'])
        self.click_get_btn.pack(side=tk.LEFT, padx=5)
        
        # 滚动参数
        tk.Label(row1_frame, text="滚动距离:", font=("微软雅黑", 9),
                bg=self.theme_colors['primary'], fg=self.theme_colors['text']).pack(side=tk.LEFT, padx=(20, 5))
        self.scroll_entry = tk.Entry(row1_frame, font=("微软雅黑", 9),
                                bg='white', fg=self.theme_colors['text'])
        self.scroll_entry.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)
        tk.Label(row1_frame, text="(正数向上，负数向下)", font=("微软雅黑", 8),
                bg=self.theme_colors['primary'], fg=self.theme_colors['text']).pack(side=tk.LEFT, padx=5)
        
        # 第二行：键盘输入和延迟时间
        row2_frame = tk.Frame(param_frame, bg=self.theme_colors['primary'])
        row2_frame.pack(fill=tk.X, pady=3)
        
        # 键盘输入参数
        tk.Label(row2_frame, text="输入内容:", font=("微软雅黑", 9),
                bg=self.theme_colors['primary'], fg=self.theme_colors['text']).pack(side=tk.LEFT, padx=(0, 5))
        self.keyboard_entry = tk.Entry(row2_frame, font=("微软雅黑", 9),
                                    bg='white', fg=self.theme_colors['text'])
        self.keyboard_entry.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)
        
        # 延迟时间
        tk.Label(row2_frame, text="延迟时间(秒):", font=("微软雅黑", 9),
                bg=self.theme_colors['primary'], fg=self.theme_colors['text']).pack(side=tk.LEFT, padx=(20, 5))
        self.delay_entry = tk.Entry(row2_frame, font=("微软雅黑", 9),
                                bg='white', fg=self.theme_colors['text'])
        self.delay_entry.insert(0, "1.0")
        self.delay_entry.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)
        
        tk.Label(row2_frame, text="操作后延迟(秒):", font=("微软雅黑", 9),
                bg=self.theme_colors['primary'], fg=self.theme_colors['text']).pack(side=tk.LEFT, padx=(20, 5))
        self.post_delay_entry = tk.Entry(row2_frame, font=("微软雅黑", 9),
                                bg='white', fg=self.theme_colors['text'])
        self.post_delay_entry.insert(0, "0.5")
        self.post_delay_entry.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)
        
        # 第三行：操作描述
        row3_frame = tk.Frame(param_frame, bg=self.theme_colors['primary'])
        row3_frame.pack(fill=tk.X, pady=3)
        
        tk.Label(row3_frame, text="操作描述:", font=("微软雅黑", 9),
                bg=self.theme_colors['primary'], fg=self.theme_colors['text']).pack(side=tk.LEFT, padx=(0, 5))
        self.desc_entry = tk.Entry(row3_frame, font=("微软雅黑", 9),
                                bg='white', fg=self.theme_colors['text'])
        self.desc_entry.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)
        
        # 循环次数
        tk.Label(row3_frame, text="循环次数:", font=("微软雅黑", 9),
                bg=self.theme_colors['primary'], fg=self.theme_colors['text']).pack(side=tk.LEFT, padx=(20, 5))
        self.loop_count_entry = tk.Entry(row3_frame, font=("微软雅黑", 9),
                                bg='white', fg=self.theme_colors['text'])
        self.loop_count_entry.insert(0, "1")
        self.loop_count_entry.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)
        
        # 初始更新参数显示
        self.update_parameter_display()
    
    def setup_buttons(self, parent):
        """设置按钮框架 - 使用淡紫色主题和响应式布局"""
        # 操作管理按钮框架
        button_frame = tk.LabelFrame(parent, text="操作管理", font=("微软雅黑", 11, "bold"),
                                   bg=self.theme_colors['primary'], fg=self.theme_colors['text'],
                                   relief=tk.GROOVE, bd=2)
        button_frame.pack(fill=tk.X, padx=5, pady=5)
        
        # 第一行按钮：主要操作按钮
        row1_frame = tk.Frame(button_frame, bg=self.theme_colors['primary'])
        row1_frame.pack(fill=tk.X, pady=3)
        
        # 使用网格布局让按钮均匀分布
        buttons_row1 = [
            ("添加操作", self.add_operation, self.theme_colors['success']),
            ("编辑操作", self.edit_operation, self.theme_colors['warning']),
            ("更新操作", self.update_operation, self.theme_colors['accent']),
            ("删除操作", self.delete_operation, self.theme_colors['error'])
        ]
        
        for i, (text, command, color) in enumerate(buttons_row1):
            btn = tk.Button(row1_frame, text=text, command=command,
                          font=("微软雅黑", 9), bg=color, fg='white',
                          activebackground=self.theme_colors['button_hover'],
                          height=1)  # 移除width参数，让按钮自适应
            btn.pack(side=tk.LEFT, padx=3, expand=True, fill=tk.BOTH) 
        
        # 第二行按钮：顺序调整按钮
        row2_frame = tk.Frame(button_frame, bg=self.theme_colors['primary'])
        row2_frame.pack(fill=tk.X, pady=3)
        
        buttons_row2 = [
            ("上移", self.move_operation_up, self.theme_colors['button']),
            ("下移", self.move_operation_down, self.theme_colors['button'])
        ]
        
        for i, (text, command, color) in enumerate(buttons_row2):
            btn = tk.Button(row2_frame, text=text, command=command,
                          font=("微软雅黑", 9), bg=color, fg='white',
                          activebackground=self.theme_colors['button_hover'],
                          height=1)  # 移除width参数，让按钮自适应
            btn.pack(side=tk.LEFT, padx=3, expand=True, fill=tk.BOTH)  # 改为fill=tk.BOTH
        
        # 文件操作按钮框架
        file_frame = tk.LabelFrame(parent, text="文件操作", font=("微软雅黑", 11, "bold"),
                                 bg=self.theme_colors['primary'], fg=self.theme_colors['text'],
                                 relief=tk.GROOVE, bd=2)
        file_frame.pack(fill=tk.X, padx=5, pady=8)
        
        file_buttons = [
            ("保存配置", self.save_config, self.theme_colors['success']),
            ("加载配置", self.load_config, self.theme_colors['accent']),
            ("清空画布", self.clear_canvas, self.theme_colors['warning'])
        ]
        
        for i, (text, command, color) in enumerate(file_buttons):
            btn = tk.Button(file_frame, text=text, command=command,
                          font=("微软雅黑", 9), bg=color, fg='white',
                          activebackground=self.theme_colors['button_hover'],
                          height=1)  # 移除width参数，让按钮自适应
            btn.pack(side=tk.LEFT, padx=5, expand=True, fill=tk.BOTH)
        
        # 开始执行按钮 - 突出显示
        execute_frame = tk.Frame(parent, bg=self.theme_colors['primary'])
        execute_frame.pack(fill=tk.X, padx=5, pady=10)
        
        self.execute_btn = tk.Button(execute_frame, text="开始执行操作序列", 
                                   command=self.start_execution,
                                   font=("微软雅黑", 12, "bold"), 
                                   bg=self.theme_colors['accent'], fg='white',
                                   activebackground=self.theme_colors['button_hover'],
                                   height=2)
        self.execute_btn.pack(fill=tk.X, pady=5)
        
        # 状态显示标签
        status_frame = tk.LabelFrame(parent, text="执行状态", font=("微软雅黑", 11, "bold"),
                                   bg=self.theme_colors['primary'], fg=self.theme_colors['text'],
                                   relief=tk.GROOVE, bd=2)
        status_frame.pack(fill=tk.X, padx=5, pady=8)
        
        self.status_label = tk.Label(status_frame, text="就绪", 
                                   font=("微软雅黑", 10), 
                                   bg=self.theme_colors['secondary'], 
                                   fg=self.theme_colors['text'],
                                   relief="sunken", height=2)
        self.status_label.pack(fill=tk.X, padx=5, pady=5)
        
        # 鼠标坐标跟踪器
        self.mouse_tracker = None
        self.tracker_thread = None
        self.click_tracker = None
    
    def on_operation_type_change(self, *args):
        """操作类型变化事件"""
        self.update_parameter_display()
    
    def on_listbox_select(self, event):
        """列表选择事件"""
        selection = self.operation_listbox.curselection()
        if selection:
            index = selection[0]
            operation = self.sequence_manager.operation_sequence[index]
            self.visual_canvas.select_operation(operation)
    
    def on_listbox_double_click(self, event):
        """列表双击事件 - 直接编辑选中的操作"""
        # 获取点击位置对应的项目索引
        index = self.operation_listbox.nearest(event.y)
        if index >= 0:
            # 设置选择并调用编辑方法
            self.operation_listbox.selection_clear(0, tk.END)
            self.operation_listbox.select_set(index)
            self.operation_listbox.see(index)
            self.edit_operation()

    def on_mouse_click(self, x, y):
        """鼠标点击回调函数"""
        self.root.after(0, self._update_coordinates, x, y)
        
        # 自动停止点击跟踪
        self.root.after(100, self.stop_click_tracking)

    def _update_coordinates(self, x, y):
        """在主线程中更新坐标显示"""
        self.coord_entry.delete(0, tk.END)
        self.coord_entry.insert(0, f"{x},{y}")
        
        # 显示提示但不阻塞界面
        self.show_temporary_message(f"点击坐标已获取: ({x}, {y})")

    def show_temporary_message(self, message):
        """显示临时消息而不阻塞界面 - 使用淡紫色主题"""
        # 创建临时消息标签
        if hasattr(self, 'temp_message_label'):
            self.temp_message_label.destroy()
            
        self.temp_message_label = tk.Label(self.root, text=message, 
                                         font=("微软雅黑", 10),
                                         bg=self.theme_colors['accent'], 
                                         fg='white')
        self.temp_message_label.place(relx=0.5, rely=0.9, anchor="center")
        
        # 3秒后自动消失
        self.root.after(3000, self._remove_temp_message)
    
    def _remove_temp_message(self):
        """移除临时消息"""
        if hasattr(self, 'temp_message_label'):
            self.temp_message_label.destroy()

    def start_click_tracking(self):
        """开始鼠标点击跟踪 - 添加程序最小化功能"""
        if self.click_tracker and self.click_tracker.running:
            # 如果已经在监听，先停止
            self.click_tracker.stop_listening()
            time.sleep(0.1)  # 短暂等待确保监听器完全停止
            
        # 最小化程序窗口
        self.root.iconify()
        
        self.click_tracker = MouseClickTracker(self.on_mouse_click)
        self.click_tracker.start_listening()
        
        # 启动ESC键监听线程
        self.esc_listener_running = True
        self.esc_listener_thread = threading.Thread(target=self._esc_key_listener, daemon=True)
        self.esc_listener_thread.start()
        
        # 更新按钮状态
        self.click_get_btn.config(text="停止点击获取", 
                                 command=self.stop_click_tracking,
                                 bg="lightcoral")
        
        self.show_temporary_message("点击获取模式已启动，程序已最小化\n请点击鼠标左键获取坐标\n按ESC键可退出点击获取模式")
    
    def _esc_key_listener(self):
        """ESC键监听线程"""
        while self.esc_listener_running:
            if keyboard.is_pressed('esc'):
                # 在主线程中停止点击跟踪
                self.root.after(0, self._stop_by_esc)
                break
            time.sleep(0.1)
    
    def _stop_by_esc(self):
        """通过ESC键停止点击跟踪"""
        self.stop_click_tracking()
        self.show_temporary_message("已通过ESC键退出点击获取模式")
    
    def stop_click_tracking(self):
        """停止鼠标点击跟踪"""
        # 停止ESC键监听
        self.esc_listener_running = False
        
        if self.click_tracker:
            self.click_tracker.stop_listening()
            
        # 恢复程序窗口
        self.root.deiconify()
        
        # 恢复按钮状态
        self.click_get_btn.config(text="点击获取坐标", 
                               command=self.start_click_tracking,
                               bg="SystemButtonFace")
    
    def update_parameter_display(self):
        """根据操作类型更新参数显示"""
        op_type = self.operation_type.get()
        
        # 显示/隐藏相关参数
        if op_type == "click":
            self.coord_entry.config(state=tk.NORMAL)
            self.scroll_entry.config(state=tk.DISABLED)
            self.keyboard_entry.config(state=tk.DISABLED)
        elif op_type == "scroll":
            self.coord_entry.config(state=tk.NORMAL)
            self.scroll_entry.config(state=tk.NORMAL)
            self.keyboard_entry.config(state=tk.DISABLED)
        elif op_type == "keyboard":
            self.coord_entry.config(state=tk.DISABLED)
            self.scroll_entry.config(state=tk.DISABLED)
            self.keyboard_entry.config(state=tk.NORMAL)
    
    def add_operation(self):
        """添加操作到序列"""
        try:
            op_type = self.operation_type.get()
            delay = float(self.delay_entry.get() or 1.0)
            post_delay = float(self.post_delay_entry.get() or 0.5)
            loop_count = int(self.loop_count_entry.get() or 1)
            description = self.desc_entry.get() or f"{op_type}操作"
            
            operation = {
                "type": op_type,
                "delay": delay,
                "post_delay": post_delay,
                "loop_count": loop_count,
                "description": description
            }
            
            if op_type == "click" or op_type == "scroll":
                # 检查坐标输入是否为空
                coord_text = self.coord_entry.get().strip()
                if not coord_text:
                    messagebox.showerror("错误", "请先输入需要点击的坐标")
                    return
                
                try:
                    x, y = map(int, coord_text.split(','))
                    operation["x"] = x
                    operation["y"] = y
                    
                    if op_type == "scroll":
                        scroll_text = self.scroll_entry.get().strip()
                        if not scroll_text:
                            messagebox.showerror("错误", "请输入滚动量")
                            return
                        scroll_amount = int(scroll_text)
                        operation["scroll_amount"] = scroll_amount
                        
                except ValueError as e:
                    if "not enough values to unpack" in str(e):
                        messagebox.showerror("错误", "坐标格式错误，请使用逗号分隔的格式，如：100,200")
                    else:
                        messagebox.showerror("错误", f"坐标格式错误：{e}")
                    return
                    
            elif op_type == "keyboard":
                text = self.keyboard_entry.get().strip()
                if not text:
                    messagebox.showerror("错误", "请输入要输入的文本")
                    return
                operation["text"] = text
            
            # 添加到管理器
            self.sequence_manager.operation_sequence.append(operation)
            
            # 更新界面
            self.update_operation_list()
            self.visual_canvas.add_operation(operation)
            self.clear_inputs()
            
            messagebox.showinfo("成功", "操作已添加到序列")
            
        except Exception as e:
            # 提供更具体的错误信息
            error_message = f"添加操作失败: {e}"
            if "ValueError" in str(type(e)):
                error_message = f"输入格式错误: {e}"
            elif "AttributeError" in str(type(e)):
                error_message = f"界面组件错误: {e}"
                
            messagebox.showerror("错误", error_message)
    
    def update_operation(self):
        """更新当前编辑的操作"""
        selection = self.operation_listbox.curselection()
        if not selection:
            messagebox.showwarning("警告", "请先选择一个要更新的操作")
            return
            
        index = selection[0]
        
        try:
            op_type = self.operation_type.get()
            delay = float(self.delay_entry.get() or 1.0)
            post_delay = float(self.post_delay_entry.get() or 0.5)
            loop_count = int(self.loop_count_entry.get() or 1)
            description = self.desc_entry.get() or f"{op_type}操作"
            
            operation = {
                "type": op_type,
                "delay": delay,
                "post_delay": post_delay,
                "loop_count": loop_count,
                "description": description
            }
            
            if op_type == "click" or op_type == "scroll":
                # 检查坐标输入是否为空
                coord_text = self.coord_entry.get().strip()
                if not coord_text:
                    messagebox.showerror("错误", "请先输入需要点击的坐标")
                    return
                
                try:
                    x, y = map(int, coord_text.split(','))
                    operation["x"] = x
                    operation["y"] = y
                    
                    if op_type == "scroll":
                        scroll_text = self.scroll_entry.get().strip()
                        if not scroll_text:
                            messagebox.showerror("错误", "请输入滚动量")
                            return
                        scroll_amount = int(scroll_text)
                        operation["scroll_amount"] = scroll_amount
                        
                except ValueError as e:
                    if "not enough values to unpack" in str(e):
                        messagebox.showerror("错误", "坐标格式错误，请使用逗号分隔的格式，如：100,200")
                    else:
                        messagebox.showerror("错误", f"坐标格式错误：{e}")
                    return
                    
            elif op_type == "keyboard":
                text = self.keyboard_entry.get().strip()
                if not text:
                    messagebox.showerror("错误", "请输入要输入的文本")
                    return
                operation["text"] = text
            
            # 更新操作序列
            self.sequence_manager.operation_sequence[index] = operation
            
            # 更新界面
            self.update_operation_list()
            self.visual_canvas.clear_canvas()
            for op in self.sequence_manager.operation_sequence:
                self.visual_canvas.add_operation(op)
            
            # 重新选择当前操作
            self.operation_listbox.select_set(index)
            self.visual_canvas.select_operation(operation)
            
            messagebox.showinfo("成功", "操作已更新")
            
        except Exception as e:
            messagebox.showerror("错误", f"更新操作失败: {e}")

    def update_operation_list(self):
        """更新操作列表显示"""
        self.operation_listbox.delete(0, tk.END)
        operation_sequence = self.sequence_manager.operation_sequence
        
        for i, op in enumerate(operation_sequence):
            # 显示更详细的操作信息
            if op["type"] == "click":
                info = f"{i+1}. {op['description']} (点击: {op['x']},{op['y']})"
            elif op["type"] == "scroll":
                info = f"{i+1}. {op['description']} (滚动: {op['scroll_amount']} at {op['x']},{op['y']})"
            elif op["type"] == "keyboard":
                text_preview = op['text'][:20] + "..." if len(op['text']) > 20 else op['text']
                info = f"{i+1}. {op['description']} (键盘: {text_preview})"
            else:
                info = f"{i+1}. {op['description']} ({op['type']})"
            
            self.operation_listbox.insert(tk.END, info)
    
    def edit_operation(self):
        """编辑选中的操作"""
        selection = self.operation_listbox.curselection()
        if not selection:
            messagebox.showwarning("警告", "请先选择一个操作")
            return
            
        index = selection[0]
        operation = self.sequence_manager.operation_sequence[index]
        
        # 填充当前操作信息到输入框
        self.operation_type.set(operation["type"])
        self.delay_entry.delete(0, tk.END)
        self.delay_entry.insert(0, str(operation["delay"]))
        self.post_delay_entry.delete(0, tk.END)
        self.post_delay_entry.insert(0, str(operation.get("post_delay", 0.5)))
        self.loop_count_entry.delete(0, tk.END)
        self.loop_count_entry.insert(0, str(operation.get("loop_count", 1)))
        self.desc_entry.delete(0, tk.END)
        self.desc_entry.insert(0, operation["description"])
        
        if operation["type"] == "click":
            self.coord_entry.delete(0, tk.END)
            self.coord_entry.insert(0, f"{operation['x']},{operation['y']}")
        elif operation["type"] == "scroll":
            self.coord_entry.delete(0, tk.END)
            self.coord_entry.insert(0, f"{operation['x']},{operation['y']}")
            self.scroll_entry.delete(0, tk.END)
            self.scroll_entry.insert(0, str(operation["scroll_amount"]))
        elif operation["type"] == "keyboard":
            self.keyboard_entry.delete(0, tk.END)
            self.keyboard_entry.insert(0, operation["text"])
        
        self.update_parameter_display()
        
        # 显示编辑提示
        self.show_temporary_message(f"正在编辑第 {index+1} 个操作")

    def delete_operation(self):
        """删除选中的操作"""
        selection = self.operation_listbox.curselection()
        if not selection:
            messagebox.showwarning("警告", "请先选择一个操作")
            return
            
        index = selection[0]
        # 从操作序列中删除
        self.sequence_manager.operation_sequence.pop(index)
        
        # 清空画布并重新绘制所有剩余的操作
        self.visual_canvas.clear_canvas()
        for operation in self.sequence_manager.operation_sequence:
            self.visual_canvas.add_operation(operation)
        
        # 更新操作列表显示
        self.update_operation_list()
    
    def move_operation_up(self):
        """上移操作 - 修复版"""
        selection = self.operation_listbox.curselection()
        if not selection or selection[0] == 0:
            return
            
        index = selection[0]
        # 交换操作序列中的元素
        operation_sequence = self.sequence_manager.operation_sequence  # 修复：使用序列管理器
        operation_sequence[index], operation_sequence[index-1] = operation_sequence[index-1], operation_sequence[index]
        
        # 更新列表显示
        self.update_operation_list()
        
        # 重新选择移动后的操作
        self.operation_listbox.select_set(index-1)
        
        # 完全重绘画布
        self.visual_canvas.clear_canvas()
        for operation in operation_sequence:
            self.visual_canvas.add_operation(operation)
        
        # 重新选择当前操作
        if index-1 < len(operation_sequence):
            self.visual_canvas.select_operation(operation_sequence[index-1])

    def move_operation_down(self):
        """下移操作 - 修复版"""
        selection = self.operation_listbox.curselection()
        if not selection or selection[0] == len(self.sequence_manager.operation_sequence)-1:  # 修复：使用序列管理器
            return
            
        index = selection[0]
        # 交换操作序列中的元素
        operation_sequence = self.sequence_manager.operation_sequence  # 修复：使用序列管理器
        operation_sequence[index], operation_sequence[index+1] = operation_sequence[index+1], operation_sequence[index]
        
        # 更新列表显示
        self.update_operation_list()
        
        # 重新选择移动后的操作
        self.operation_listbox.select_set(index+1)
        
        # 完全重绘画布
        self.visual_canvas.clear_canvas()
        for operation in operation_sequence:
            self.visual_canvas.add_operation(operation)
        
        # 重新选择当前操作
        if index+1 < len(operation_sequence):
            self.visual_canvas.select_operation(operation_sequence[index+1])
    
    def update_operation_list(self):
        """更新操作列表显示"""
        self.operation_listbox.delete(0, tk.END)
        operation_sequence = self.sequence_manager.operation_sequence
        
        for i, op in enumerate(operation_sequence):
            # 显示更详细的操作信息
            if op["type"] == "click":
                info = f"{i+1}. {op['description']} (点击: {op['x']},{op['y']})"
            elif op["type"] == "scroll":
                info = f"{i+1}. {op['description']} (滚动: {op['scroll_amount']} at {op['x']},{op['y']})"
            elif op["type"] == "keyboard":
                text_preview = op['text'][:20] + "..." if len(op['text']) > 20 else op['text']
                info = f"{i+1}. {op['description']} (键盘: {text_preview})"
            else:
                info = f"{i+1}. {op['description']} ({op['type']})"
            
            self.operation_listbox.insert(tk.END, info)
    
    def clear_inputs(self):
        """清空输入框"""
        self.coord_entry.delete(0, tk.END)
        self.scroll_entry.delete(0, tk.END)
        self.keyboard_entry.delete(0, tk.END)
        self.desc_entry.delete(0, tk.END)
        self.delay_entry.delete(0, tk.END)
        self.delay_entry.insert(0, "1.0")
        self.post_delay_entry.delete(0, tk.END)
        self.post_delay_entry.insert(0, "0.5")
        self.loop_count_entry.delete(0, tk.END)
        self.loop_count_entry.insert(0, "1")
    
    def clear_canvas(self):
        """清空画布"""
        self.visual_canvas.clear_canvas()
        self.sequence_manager.operation_sequence = []  # 修复：使用序列管理器
        self.update_operation_list()
        messagebox.showinfo("成功", "画布已清空")
    
    def save_config(self):
        """保存配置到文件 - 修复版"""
        try:
            # 使用序列管理器保存配置
            if self.sequence_manager.save_sequence_to_file():
                messagebox.showinfo("成功", "配置已保存")
            else:
                messagebox.showwarning("警告", "保存操作已取消")
        except Exception as e:
            messagebox.showerror("错误", f"保存失败: {e}")

    def load_config(self):
        """从文件加载配置 - 修复版"""
        try:
            # 使用序列管理器加载配置
            if self.sequence_manager.load_sequence_from_file():
                # 更新界面
                self.update_operation_list()
                self.visual_canvas.clear_canvas()
                for operation in self.sequence_manager.operation_sequence:
                    self.visual_canvas.add_operation(operation)
                messagebox.showinfo("成功", "配置已加载")
            else:
                messagebox.showwarning("警告", "加载操作已取消")
        except Exception as e:
            messagebox.showerror("错误", f"加载失败: {e}")

    def browse_txt_file(self):
        """浏览文本文件"""
        filename = filedialog.askopenfilename(
            filetypes=[("Text files", "*.txt"), ("All files", "*.*")],
            title="选择文本文件"
        )
        if filename:
            self.txt_path_entry.delete(0, tk.END)
            self.txt_path_entry.insert(0, filename)

    def _execute_in_thread(self):
        """在新线程中执行操作序列"""
        def status_callback(message):
            self.root.after(0, lambda: self.status_label.config(
                text=message, bg=self.theme_colors['accent']))
        
        try:
            # 执行操作序列（不再需要模式参数）
            success = self.sequence_manager.execute_sequence(
                callback=status_callback
            )
            
            # 执行完成
            if success:
                self.root.after(0, lambda: self.status_label.config(
                    text="执行完成", bg=self.theme_colors['success']))
                self.root.after(0, lambda: messagebox.showinfo("完成", "所有操作执行完成！"))
            else:
                self.root.after(0, lambda: self.status_label.config(
                    text="用户取消执行", bg=self.theme_colors['secondary']))
                
        except Exception as e:
            self.root.after(0, lambda: self.status_label.config(
                text=f"执行出错: {e}", bg=self.theme_colors['error']))
            self.root.after(0, lambda: messagebox.showerror("错误", f"执行过程中出错: {e}"))
    
    def start_execution(self):
        """开始执行操作序列"""
        if not self.sequence_manager.operation_sequence:
            messagebox.showwarning("警告", "请先添加操作序列")
            return
            
        # 更新状态
        self.status_label.config(text="准备执行操作序列...", bg=self.theme_colors['warning'])
        self.root.update()
        
        # 询问用户是否准备好
        result = messagebox.askyesno("确认执行", 
                                   f"即将开始执行操作序列。\n\n"
                                   f"操作数量: {len(self.sequence_manager.operation_sequence)}\n\n"
                                   "请在5秒内将目标窗口置于前台。\n"
                                   "按F2键可随时退出执行。\n\n"
                                   "是否继续？")
        if not result:
            self.status_label.config(text="已取消", bg=self.theme_colors['secondary'])
            return
        
        # 在新线程中执行操作序列
        execution_thread = threading.Thread(target=self._execute_in_thread, daemon=True)
        execution_thread.start()

